import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TalkingRoom extends JFrame {
    private JScrollPane showPan=new JScrollPane();//信息显示滚动容器
    private Box box =Box.createVerticalBox();//信息显示垂直盒子容器
    private JScrollPane inputPan=new JScrollPane();//输入信息滚动容器
    private JTextArea textArea=new JTextArea();//输入框
    private JButton sendbtn = new JButton("发送");//发送按钮
    private URL url=TalkingRoom.class.getResource("胡萝卜.png");//获取TalkingRoom.class目录下的其他文件路径
    private ImageIcon icon=new ImageIcon(url);//生成图片文件
//    private ImageIcon icon=new ImageIcon("src/胡萝卜.png");//生成图片文件
    private MyListener myListener =new MyListener();
    private Socket socket;//
    private String name="";


    public TalkingRoom(){

        while ("".equals(name)){
            name=JOptionPane.showInputDialog(this,"请输入昵称","请输入昵称",1);
            if (name==null)System.exit(0);
            if ("".equals(name)){
                JOptionPane.showMessageDialog(this,"昵称不能为空！","警告",2);
            }else if (name.getBytes().length>18){
                JOptionPane.showMessageDialog(this,"昵称不能超过16字节（6个中文字）！","警告",2);
                name="";
            }
        }
        setLayout(null);//设置布局为绝对布局

        sendbtn.setBounds(400,500,60,30);//设置按钮位置和大小
        showPan.setBounds(23,5,440,380);//显示框
        inputPan.setBounds(23,390,440,100);//输入框

        showPan.setBorder(BorderFactory.createEtchedBorder());//显示框边框
//        showPan.setBackground(Color.white);
        showPan.setViewportView(box);//设置显示框滚动视图组件
//        box.setBackground(Color.white);
        inputPan.setViewportView(textArea);//设置输入框滚动视图组件


        sendbtn.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (socket!=null)
                SendMsg(textArea.getText());
            }
        });

        textArea.addKeyListener(myListener);

        add(sendbtn);
        add(showPan);
        add(inputPan);
        setTitle("聊天室-"+name);//设置标题
        setVisible(true);//显示窗口
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按钮可以关闭程序
        setBounds(710,300,500,600);//窗口出现位置以及高宽
        setIconImage(icon.getImage());//设置窗体图标
        setResizable(false);//不允许拉伸窗口

//        talkingService=new TalkingService(this);
//        talkingService.run();
    }

    public void SendMsg(String msg){
//        addMsg(msg,BorderLayout.EAST,new Color(135,206,250));
        try {
            if (msg.length()>0){
                textArea.setText(null);
                Message message=new Message();
                message.setName(name);
                message.setAddress(socket.getLocalAddress().toString());
                message.setPort(socket.getLocalPort());
                message.setMsg(msg);
                message.setDate(new Date());
                socket.getOutputStream().write(JSONObject.toJSONString(message).getBytes("UTF-8"));
            }else {

            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        textArea.setText("");
        inputPan.setViewportView(textArea);
        textArea.grabFocus();
    }

    public void GetMsg(Message msg){
        addMsg(msg);
    }



    private void addMsg(Message ms){

        Component verticalStrut = Box.createVerticalStrut(20);//信息间距
        Meg meg=null;
//        verticalStrut.setBackground(Color.WHITE);
//        System.out.println("address:"+ms.getAddress()+"prot:"+ms.getPort());
//        System.out.println("socket:"+socket.getLocalAddress()+"prot:"+socket.getLocalPort());
//        System.out.println("address: "+ms.getAddress().equals(socket.getLocalAddress().toString()));
//        System.out.println("port:"+(ms.getPort()==socket.getLocalPort()));
        if (socket!=null&&ms.getAddress().equals(socket.getLocalAddress().toString())&&ms.getPort()==socket.getLocalPort()){
            meg=new Meg(ms,"East",new Color(135,206,250));
        }else {
            meg=new Meg(ms,"West",new Color(251,185,197));
        }

        box.add(meg);
        box.add(verticalStrut);
        showPan.setViewportView(box);

        JScrollBar jscrollBar = showPan.getVerticalScrollBar();//使滚动条移至最下
        if (jscrollBar != null)
            jscrollBar.setValue(jscrollBar.getMaximum());
    }

    public MyListener getMyListener() {
        return myListener;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    //事件监听
    class MyListener implements KeyListener {
        @Override // 按下
        public void keyPressed(KeyEvent e) {
//            textArea.append("按下："+KeyEvent.getKeyText(e.getKeyCode()) + "\n");

        }
        @Override // 松开
        public void keyReleased(KeyEvent e) {
//            textArea.append("松开：" + KeyEvent.getKeyText(e.getKeyCode()) + "\n");
            if ("Enter".equals(KeyEvent.getKeyText(e.getKeyCode()))){
                if (socket!=null)
                SendMsg(textArea.getText());
            }
        }
        @Override // 输入的内容
        public void keyTyped(KeyEvent e) {
//            textArea.append("输入：" + e.getKeyChar() + "\n");
        }

    }


    class Meg extends JPanel {
        private Message message;
        Meg(Message m,String NESW,Color color){
            message=m;

//            JLabel jLabel=new JLabel("<html><h3>"+message.getName()+":</h3><font size='5'>"+message.getMsg()+"</font></html>",
            JLabel jLabel=new JLabel("<html>" +
                    "<font size='3'>"+message.getName()+"</font>" +
                    "<div></div>" +
                    "<font size='5'>"+message.getMsg()+"</font>" +
                    "</html>",
                    SwingConstants.RIGHT);
            jLabel.setHorizontalAlignment(SwingConstants.RIGHT);

            JPanel jp=new JPanel(new BorderLayout());
            jp.add(jLabel,BorderLayout.CENTER);
            jp.setBackground(color);
//            jp.setBorder(new RoundBorder(new Color(135,206,250)));

            setLayout(new BorderLayout());
            setSize(400,30);
//            setBackground(Color.white);
//            setPreferredSize(new Dimension(400, 20));
            setMaximumSize(new Dimension(400, 60));//设置Meg的最大样式
            setMinimumSize(new Dimension(400, 60));//设置Meg的最小样式
            add(jp,NESW);
        }
    }

    class RoundBorder implements Border {
        private Color color;

        public RoundBorder(Color color) {// 有参数的构造方法
            this.color = color;
        }

        public RoundBorder() {// 无参构造方法
            this.color = Color.BLACK;
            // 如果实例化时，没有传值
            // 默认是黑色边框
        }

        public Insets getBorderInsets(Component c) {
            return new Insets(0, 0, 0, 0);
        }

        public boolean isBorderOpaque() {
            return false;
        }

        // 实现Border（父类）方法
        @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width,
                                int height) {
            g.setColor(color);
            g.drawRoundRect(0, 0, c.getWidth() - 1, c.getHeight() - 1, 15, 15);
        }
    }

}
